import { Component } from 'react';
import Taro, { Config,getCurrentInstance,eventCenter  } from '@tarojs/taro';
import { View, ScrollView, Image, Text } from '@tarojs/components'
import { connect } from 'react-redux'
import classnames from 'classnames'
import { debounce,staticUrl } from '@/utils'
import Iconfont from '@/components/Iconfont'
import CarInfo from '@/components/CarInfo'
import navigationTo from '@/utils/command'
import { storeGoods, controlInsuranceBtn, getConfig } from '@/api'
import { getGoodsDistributionIndex } from '@/api/goods/distribution'
import BannerView from '../banner'
import './index.scss'

const icon_version = 'icon-v3'
const sdby_version = 'sdby-v1'
const csmr_version = 'csmr-v1'
const cnxd_version = 'cnxd-v1'
const aqsj_version = 'aqsj-v1'
const dppj_version = 'dppj-v1'
const xpss_version = 'xpss-v1'
const jpgz_version = 'jpgz-v1'
const fdj_version = 'fdj-v1'
const rmbt_version = 'rmbt-v1'
const air_version = 'air-v1'

const couponIcon = staticUrl('/img/index/coupon-icon.png')
const cartIcon = staticUrl('/img/index/cart-icon.png')
// 热门必推
const rmbtIcon = staticUrl(`/img/index/hot.png`)
const label = staticUrl(`/img/index/${rmbt_version}/label.png`)
const generalize = staticUrl(`/img/index/${rmbt_version}/generalize.png`)

// 2021.3.23需求用下面的绿色图标
const qichemeirong1 = staticUrl(`/img/index/${icon_version}/qichemeirong1.png?v=3`)
const baoyang1 = staticUrl(`/img/index/${icon_version}/baoyang1.png?v=3`)
const chexian1 = staticUrl(`/img/index/${icon_version}/chexian1.png?v=3`)
const nianka1 = staticUrl(`/img/index/${icon_version}/nianka1.png?v=3`)
const luntai1 = staticUrl(`/img/index/${icon_version}/luntai1.png?v=3`)
const meirong1 = staticUrl(`/img/index/${icon_version}/meirong1.png?v=3`)
const ktby1 = staticUrl(`/img/index/${icon_version}/ktby1.png?v=3`)
const cjt1 = staticUrl(`/img/index/${icon_version}/cjt1.png?v=3`)
const qcjp1 = staticUrl(`/img/index/${icon_version}/xcjp1.png?v=3`)
const gzImg1 = staticUrl(`/img/index/${icon_version}/gz-img1.png?v=3`)

// 空调养护
const airIcon = staticUrl(`/img/index/${air_version}/air-icon.png?v=3`)
const airA1 = staticUrl(`/img/index/${air_version}/air-a-1.png?v=3`)
const airA2 = staticUrl(`/img/index/${air_version}/air-a-2.png?v=3`)
const airA3 = staticUrl(`/img/index/${air_version}/air-a-3.png?v=3`)

// 车身美容
const csmrIcon = staticUrl(`/img/index/${csmr_version}/csmr-icon.png?v=3`)

// 安全升级
const aqsjIcon = staticUrl(`/img/index/${aqsj_version}/aqsj-icon.png`)
const aqsjB1 = staticUrl(`/img/index/${aqsj_version}/aqsj-b-1.png`)
const aqsjS1 = staticUrl(`/img/index/${aqsj_version}/aqsj-s-1.png`)
const aqsjS2 = staticUrl(`/img/index/${aqsj_version}/aqsj-s-2.png`)
// 大牌配件
const dppjIcon = staticUrl(`/img/index/${dppj_version}/dppj-icon.png`)
const dppjB1 = staticUrl(`/img/index/${dppj_version}/dppj-b-1.png`)
const dppjS1 = staticUrl(`/img/index/${dppj_version}/dppj-s-1.png`)
const dppjS2 = staticUrl(`/img/index/${dppj_version}/dppj-s-2.png`)

// 精品改装1
const jpIcon = staticUrl(`/img/index/${jpgz_version}/jp-icon.png?v=4`)

// 精品改装2
const jpB21 = staticUrl(`/img/index/${jpgz_version}/jpgz-4.png?v=4`)
const jpS21 = staticUrl(`/img/index/${jpgz_version}/jpgz-5.png?v=4`)
const jpS22 = staticUrl(`/img/index/${jpgz_version}/jpgz-6.png?v=4`)
// 精品改装3
const jpC1 = staticUrl(`/img/index/${jpgz_version}/jpgz-c1.png?v=4`)
const jpC2 = staticUrl(`/img/index/${jpgz_version}/jpgz-c2.png?v=4`)
const jpC3 = staticUrl(`/img/index/${jpgz_version}/jpgz-c3.png?v=4`)

// 0元镀金
const jpD1 = staticUrl(`/img/index/${jpgz_version}/jpdj-a1.png?v=1`)
const jpD2 = staticUrl(`/img/index/${jpgz_version}/jpdj-a2.png?v=1`)
const jpD3 = staticUrl(`/img/index/${jpgz_version}/jpdj-a3.png?v=1`)

const layoutView = [
  {
    icon: csmrIcon,
    title: '0元镀晶',
    command: null,
    imgs: [{
      url: jpD1,
      command: {
        commandName: 'annual-order',
        query: {
          annualCardId: 411,
          type: 1
        }
      }
    }, {
      url: jpD2,
      command: {
        commandName: 'annual-order',
        query: {
          annualCardId: 695,
          type: 1
        }
      }
    }, {
      url: jpD3,
      command: {
        commandName: 'annual-order',
        query: {
          annualCardId: 413,
          type: 1
        }
      }
    }]
  },
  {
    icon: airIcon,
    title: '空调养护',
    command: null,
    imgs: [{
      url: airA1,
      command: {
        commandName: 'goods',
        query: {
          id: 70391
        }
      }
    }, {
      url: airA2,
      command: {
        commandName: 'goods',
        query: {
          id: 70393
        }
      }
    }, {
      url: airA3,
      command: {
        commandName: 'goods',
        query: {
          id: 70395
        }
      }
    }]
  },
  {
    icon: jpIcon,
    title: '精品改装',
    command: null,
    imgs: [{
      url: jpC1,
      command: {
        commandName: 'goods',
        query: {
          id: 71329
        }
      }
    }, {
      url: jpC2,
      command: {
        commandName: 'goods',
        query: {
          id: 71285
        }
      }
    }, {
      url: jpC3,
      command: {
        commandName: 'goods',
        query: {
          id: 71413
        }
      }
    }]
  },
  {
    icon: jpIcon,
    title: '精品改装',
    command: null,
    imgs: [{
      url: jpB21,
      command: {
        commandName: 'goodsList',
        query: {
          id: 117
        }
      }
    }, {
      url: jpS21,
      command: {
        commandName: 'goodsList',
        query: {
          id: 89
        }
      }
    }, {
      url: jpS22,
      command: {
        commandName: 'goodsList',
        query: {
          id: 73
        }
      }
    }]
  },
  {
    icon: aqsjIcon,
    title: '安全升级',
    command: null,
    imgs: [{
      url: aqsjB1,
      command: {
        commandName: 'goodsList',
        query: {
          id: 22
        }
      }
    }, {
      url: aqsjS1,
      command: {
        commandName: 'goodsList',
        query: {
          id: 75
        }
      }
    }, {
      url: aqsjS2,
      command: {
        commandName: 'goodsList',
        query: {
          id: 117
        }
      }
    }]
  },
  {
    icon: dppjIcon,
    title: '大牌配件',
    command: null,
    imgs: [{
      url: dppjB1,
      command: {
        commandName: 'goodsList',
        query: {
          id: 68
        }
      }
    }, {
      url: dppjS1,
      command: {
        commandName: 'goodsList',
        query: {
          id: 27
        }
      }
    }, {
      url: dppjS2,
      command: {
        commandName: 'goodsList',
        query: {
          id: 31
        }
      }
    }]
  }
]

interface ProductList {
  categoryId: number
  offsetTop?: number | undefined
  itemId: number
  command: ICommand
  itemType: number
  redirectType: number
  servicePic: string
  thumbnailUrl: string
  salePrice: string
  itemTitle: string
}
interface CategoryList {
  offsetTop: number | undefined
  id: number
  title: string
}

interface Product {
  categoryList: Array<CategoryList>
  productList: Array<ProductList>
}

interface State {
  product: Product | null
  store: null
  isFixedMenu: boolean
  tabIndex: number
  menuDom: any
  scrollTo: number
  visibleInsurance: number | boolean
  swiperImgList: any
  hotGoodsList: any
}
interface Props {
  store: null
}
@connect<any>(({ car }) => ({
  car: car.carInfo.currentCar
}))
export default class MainView extends Component<State> {
	$instance = getCurrentInstance()
  constructor() {
    super(...arguments)
    const props: Props = this.props

    this.state = {
      ...props,
      isFixedMenu: false,
      tabIndex: 0,
      product: null,// 门店商品接口
      menuDom: {},
      scrollTo: 0,
      visibleInsurance: 0,// 保险按钮显示 1 显示 0 不显示
      swiperImgList: [], // newImgList 轮播图数据
      hotGoodsList: [],// 分销列表
    }
  }
  state: State
	static options = {
    addGlobalClass: true
  }

  UNSAFE_componentWillMount() { }
  componentDidMount() {
    // 保险按钮显示 return show 1/0
    controlInsuranceBtn().then(res => {
      const { show } = res.data.data
      this.setState({
        visibleInsurance: show
      })
    })
    // 门店商品接口
    this.getStoreGoods()
    // 获取首页配置
    this.getConfig()
    // 获取获取分销列表
    this.getGoodsDistributionIndex()
  }

  UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
    const { store } = nextProps
    if (this.state.store) {
      if (this.state.store.adCode !== store.adCode) {
        this.getConfig()
        this.setState({
          //swiperImgList: newImgList,
          store
        }, () => this.getStoreGoods())
      }
    }
  }
	componentWillMount () {
    const onReadyEventId = this.$instance.router.onReady
    eventCenter.once(onReadyEventId, () => {
      console.log('onReady')

      // onReady 触发后才能获取小程序渲染层的节点
      Taro.createSelectorQuery().select('#only')
        .boundingClientRect()
        .exec(res => console.log(res, 'res'))
    })
  }
  componentWillUnmount() { }

  // 门店商品接口
  getStoreGoods() {
    storeGoods().then(res => {
      const data = res.data.data
      this.setState({
        product: data
      }, () => {
      })
    })
  }

  // 获取首页轮播图
  getConfig() {
    getConfig().then(res => {
      const data = res.data.data
      const { banner } = data
      let romoteBanners: any = []
      for (let i in banner) {
        let command: any = {}
        let query: any = {}
        if (Number(banner[i].linkType) === 1) {
          query.path = '/topic/common'
          query.id = banner[i].link
          query.shareTitle = '周年庆'
          command = {
            commandName: 'topic',
            query
          }
        } else if (Number(banner[i].linkType) === 2) {
          query.id = banner[i].link
          command = {
            commandName: 'goodsList',
            query
          }
        } else if (Number(banner[i].linkType) === 3) {
          query.goodsId = banner[i].link
          command = {
            commandName: 'goods',
            query
          }
        }

        romoteBanners.push({
          url: banner[i].imgUrl,
          command
        })
      }
      this.setState({
        swiperImgList: romoteBanners,
      })
    })
  }

  // 监听页面滑动
  scrollPage = debounce((e) => {
    const { scrollTop } = e.target
		console.log('scrollTop',e)
    const { menuDom, isFixedMenu, product, tabIndex } = this.state
    if (!product) return
    for (let i = product.categoryList.length; i; i--) {
      const curCategory: CategoryList = product.categoryList[i - 1]
      const topVal = curCategory.offsetTop
      if (topVal) {
        if (scrollTop + menuDom.height > topVal) {
          if (tabIndex !== curCategory.id) {
            this.setState({
              tabIndex: curCategory.id
            })
          }
          break
        }
      }
    }
    if (scrollTop >= menuDom.top) {
      if (!isFixedMenu) {
        this.setState({
          isFixedMenu: true
        })
      }
    } else {
      if (isFixedMenu) {
        this.setState({
          isFixedMenu: false
        })
      }
    }
  }, 10)

  static config: Config = {}
  componentDidShow() {
    // 获取获取分销列表
    this.getGoodsDistributionIndex()
  }
  componentDidHide() { }
  componentDidCatchError() { }
  componentDidNotFound() { }

  // 切换标签
  tabGoods(idx: number) {
    const { product } = this.state
    if (!product) return
    this.setState({
      scrollTo: product.categoryList[idx].offsetTop
    })
  }

  // 获取分销列表
  getGoodsDistributionIndex() {
    getGoodsDistributionIndex({}).then(res => {
      if (res && res.data.success) {
        let arr = res.data.data
        let hotGoodsList = []
        if (arr.length >= 3) {
          // console.log('多于3');
          hotGoodsList = arr.slice(0, 3)
        } else if (arr.length > 0) {
          hotGoodsList = Array(3).fill(arr[0])
        }
        this.setState({
          hotGoodsList
        })
      }
    })
  }

  // 图片组件点击跳转
  onLayoutView(val) {
    const { car } = this.props
    // 跳转年卡订单确认， 如果没车辆，进入我的车库添加
    if (val.commandName == 'annual-order') {
      if (car) {
        navigationTo(val)
      } else {
        Taro.navigateTo({
          url: '/pages/car/add/index'
        })
      }
    } else {
      navigationTo(val)
    }
  }

  // 热门必推
  promotion() {
    const { hotGoodsList } = this.state
    return <View className="promotion">
      <View className="promotion-head">
        <Image lazyLoad className='text-img' src={rmbtIcon} />
        <View className="text">热门必推</View>
      </View>
      <View className="promotion-body" onClick={() => Taro.navigateTo({ url: '/pages/goods/distributionList/index' })}>
        {
          hotGoodsList.map(item => {
            return <View className="promotion-body-item" key={item.id}>
              <Image lazyLoad className='goods-img' src={item.goodsThumbnail} />
              <View className="goods-info">
                <View className="goods-name">
                  <Image lazyLoad className='label-img' src={label} />
                  <View className="goods-title">{item.goodsName}</View>
                </View>
                <View className="goods-operation">
                  <View><Text className="make-mone">赚￥</Text> <Text className="price">{item.directlyCommissionPrice}</Text> </View>
                  <View><Image lazyLoad className='generalize-img' src={generalize} /></View>
                </View>
              </View>
            </View>
          })
        }
      </View>
    </View>
  }

  render() {

    const { product, store, isFixedMenu, tabIndex, scrollTo, visibleInsurance, swiperImgList, hotGoodsList } = this.state
    let hideIcon = false
    if (store) {
      hideIcon = ['6022R001'].includes(store.storeCode)
    }
    return store && (
      <View>
        <ScrollView
          scrollY
          onScroll={this.scrollPage.bind(this)}
          scrollTop={scrollTo}
          className='location-suc'
        >
          <View className='top-bg'></View>
          <View className='store-info' style='margin-top: 20rpx'>
            <View className='store-info-content' >
              {/* 切换常用门店 */}
              <View className='store-info-context' onClick={() => Taro.navigateTo({ url: '/pages/store/index/index' })}>
                <View className='name'>
                  <View className='strong'>
                    {store.storeName}
                    <View className='icon'>
                      <View className='arrow'><Iconfont size='22' color='12B3FF' name='icon-jiantourukou' /></View>
                    </View>
                  </View>
                </View>
                <View className='address'>{store.address}</View>
              </View>
              {/* 拨打电话 */}
              <View className='phone' onClick={() => Taro.makePhoneCall({ phoneNumber: store.phone })}><Iconfont size='44' color='#fff' name='icon-zu29' /></View>
            </View>
            {/* 使用微信内置地图查看位置 */}
            <View className='store-distance' onClick={() => {
              const { latitude, longitude, address, storeName } = store
              Taro.openLocation({
                latitude: Number(latitude),
                longitude: Number(longitude),
                scale: 18,
                name: storeName,
                address
              })
            }}
            >
              <Iconfont size='44' color='#fff' name='icon-daohang' />
              <View className='num'>{store.distance}</View>
            </View>
          </View>
          <View className='view-group'>
            <View className='car-content'>
              <CarInfo styleView='2' />
            </View>
            <View>
            </View>
            <View className='card-hd no-border' onClick={() => Taro.navigateTo({ url: '/pages/service/index/index' })}>
              <View className='text'>
                <Image lazyLoad className='text-img' src={couponIcon} />
                    我的余额
              </View>
              <View className='more'>
                <View className='span'>红包、年卡、优惠券</View>
                <Iconfont size='30' color='#CCCCCC' name='icon-jiantourukou' />
              </View>
            </View>
          </View>

          {/* 轮播图 */}
          {swiperImgList.length > 0 && <BannerView imageInfo={swiperImgList}></BannerView>}
          <View className='view-group'>
            <View className='nav-content'>
              {
                hideIcon !== true && (
                  <View className='nav-list' onClick={() => { navigationTo({ commandName: 'goodsList', query: { id: 1 } }) }}>
                    <Image lazyLoad className='text-img' src={qichemeirong1} />
                    <View className='nav-text'>汽车美容</View>
                  </View>
                )
              }
              <View className='nav-list' onClick={() => { navigationTo({ commandName: 'goodsList', query: { id: 17 } }) }}>
                <Image lazyLoad className='text-img' src={baoyang1} />
                <View className='nav-text'>机油保养</View>
              </View>
              {
                visibleInsurance && (
                  <View className='nav-list'>
                    <Image lazyLoad className='text-img' src={chexian1} onClick={() => { Taro.navigateTo({ url: '/pages/webview/index/index' }) }} />
                    <View className='nav-text'>3折车险</View>
                  </View>
                )
              }
              <View className='nav-list' onClick={() => Taro.navigateTo({ url: '/pages/annual/index/index' })}>
                <Image lazyLoad className='text-img' src={nianka1} />
                <View className='nav-text'>年卡</View>
              </View>
              <View className='nav-list' onClick={() => { navigationTo({ commandName: 'goodsList', query: { id: 25 } }) }}>
                <Image lazyLoad className='text-img' src={luntai1} />
                <View className='nav-text'>换轮胎</View>
              </View>
              {
                hideIcon !== true && (
                  <View className='nav-list' onClick={() => { navigationTo({ commandName: 'goodsList', query: { id: 5 } }) }}>
                    <Image lazyLoad className='text-img' src={meirong1} />
                    <View className='nav-text'>打蜡镀晶</View>
                  </View>
                )
              }
              <View className='nav-list' onClick={() => { navigationTo({ commandName: 'goodsList', query: { id: 46 } }) }}>
                <Image lazyLoad className='text-img' src={ktby1} />
                <View className='nav-text'>空调保养</View>
              </View>
              <View className='nav-list' onClick={() => { navigationTo({ commandName: 'goodsList', query: { id: 37 } }) }}>
                <Image lazyLoad className='text-img' src={cjt1} />
                <View className='nav-text'>除积碳</View>
              </View>
              <View className='nav-list' onClick={() => { navigationTo({ commandName: 'goodsList', query: { id: 94 } }) }}>
                <Image lazyLoad className='text-img' src={qcjp1} />
                <View className='nav-text'>汽车精品</View>
              </View>
              <View className='nav-list' onClick={() => { navigationTo({ commandName: 'goodsList', query: { id: 70 } }) }}>
                <Image lazyLoad className='text-img' src={gzImg1} />
                <View className='nav-text'>改装</View>
              </View>
            </View>
          </View>
          {hotGoodsList.length > 0 ? this.promotion() : ''}
          {
            layoutView.map((layout) => {
              return (
                <View key={layout.title} className='view-group'>
                  <View className='card-hd'>
                    <View className='text'>
                      <Image lazyLoad className='text-img' src={layout.icon} />
                      {layout.title}
                    </View>
                    {
                      layout.command && (
                        <View className='more' onClick={() => this.onLayoutView(layout.command)}>
                          <View className='span'>查看更多</View>
                          <Iconfont size='30' color='#CCCCCC' name='icon-jiantourukou' />
                        </View>
                      )
                    }
                  </View>
                  <View className='grid-layout'>
                    {
                      layout.imgs.map(pic => {
                        return (
                          <View key={pic.url} onClick={() => this.onLayoutView(pic.command)} className='child-View'>
                            <Image lazyLoad className='img' src={pic.url} />
                          </View>
                        )
                      })
                    }
                  </View>
                </View>
              )
            })
          }
          {
            product && (
              <View className='goods-menu'>
                <View className={classnames('menu', isFixedMenu && 'fixed')}>
                  {
                    product.categoryList.map((v, idx) => {
                      return (
                        <View key={v.id} onTouchEnd={() => this.tabGoods(idx)} className={classnames('child-menu', tabIndex === v.id && 'curr')}>
                          <View className='text'>{v.title}</View>
                        </View>
                      )
                    })
                  }
                </View>
              </View>
            )
          }
          {
            product && (
              <View className='goods-content'>
                {
                  product.productList.map((v: ProductList) => {
                    return (
                      <View key={v.itemId} onClick={() => navigationTo(v.command)} className='goods-list'>
                        {
                          v.itemType === 1 ? (<Image lazyLoad src={v.servicePic} mode='aspectFill' className='service-goods-pic'></Image>) : (
                            <View className='goods-wrap'>
                              <Image lazyLoad src={v.thumbnailUrl} className='goods-pic'></Image>
                              <View className='name'>{v.itemTitle}</View>
                              <View className='price-info'>
                                <View className='price'>{Number(v.salePrice)}</View>
                                <Image lazyLoad src={cartIcon} className='cart-img'></Image>
                              </View>
                            </View>
                          )
                        }
                      </View>
                    )
                  })
                }
              </View>
            )
          }
        </ScrollView>
      </View>
    )
  }
}
